package higherfunction;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @Description: 简单流-收集
 * @Author: tfq
 * @Date: 2025-02-17 11:30
 */
public class SimpleStreamCollect<T> {
    private Collection<T> collection;

    public SimpleStreamCollect(Collection<T> collection) {
        this.collection = collection;
    }

    public static <T> SimpleStreamCollect<T> of(Collection<T> collection) {
        return new SimpleStreamCollect<>(collection);
    }

    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 4, 5, 2, 3, 12, 5);
        HashSet collect = SimpleStreamCollect.of(list).collect(() -> new HashSet(), (set, t) -> set.add(t));
        System.out.println(collect);
        HashMap collect2 = SimpleStreamCollect.of(list).collect(() -> new HashMap<>(), (map, t) -> map.put(t,t));
        System.out.println(collect2);
    }

    /**
     * 收集流中的元素
     *
     * @param supplier 用来创建容器
     * @param <C>      代表容器类型
     * @param consumer 要添加元素到容器的对象
     * @return 已添加元素到容器的对象
     */
    public <C> C collect(Supplier<C> supplier, BiConsumer<C, T> consumer) {
        C c = supplier.get(); //创建容器
        for (T t : collection) {
            consumer.accept(c, t); //向容器中添加元素
        }
        return c;
    }

}